<?php

/**
 * 上传图片
 * User: Grz
 * Date: 2022/04/11
 */

namespace App\Http\Controllers\OpenApi\App;

use App\Http\Controllers\Controller;
use App\Library\Service\Upload;
use Illuminate\Http\Request;

class FileController extends Controller
{
    /**
     * 接收上传图片
     * @param Request $request
     * @return array
     */
    public function upload(Request $request)
    {
        set_time_limit(0);
        $file = $request->file('file');
        $source = trim($request->input('source'));
        $img_type = trim($request->input('img_type'));
        if (empty($source)) {
            return alert_info(1, '非法操作！');
        }
        if (empty($file)) {
            return alert_info(1, '未上传文件！');
        }
        $dst_dir = 'file' . DIRECTORY_SEPARATOR;
        $Upload = (new Upload());
        $extension = strtolower($file->getClientOriginalExtension());
        if (in_array($extension, config('sys.allow_img_type'))) {
            $Upload->setMaxFileSize('10M');
        } else {
            $Upload->setMaxFileSize('35M');
        }
        $res = $Upload->setIsUploadCloud(true)->uploadFile($file, $dst_dir);
        if ($res['code'] !== 0) {
            return alert_info(1, $res['msg']);
        }
        $file_data = $res['data'];
        $file_path = $file_data['store_name'];
        $file_url = easy_cloud_attached($file_path);
        if ($img_type == 'cookbook' && in_array($extension, config('sys.allow_img_type'))) {
            $file_url = easy_cloud_attached($file_path, '400x300');
        }
        $file_path = str_replace('\\', '/', $file_path);
        return alert_info(0, '上传成功！', ['file_path' => $file_path, 'file_url' => $file_url]);
    }
}
